<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title></title>
    <link href="../../component/layui/css/layui.css" rel="stylesheet" />
    <link href="../../admin/css/pearCommon.css" rel="stylesheet" />
    <title>业务要素</title>
</head>

<body>

    <body class="pear-container">
        <div class="layui-card">
            <div class="layui-card-body">
                <form action="" class="layui-form">
                    <div class="layui-form-item">
                        <label class="layui-form-label">要素名称</label>
                        <div class="layui-input-inline">
                            <input class="layui-input" id="demoReload" name="elementName" placeholder="" type="text">
                        </div>
                        <a class="pear-btn pear-btn-md pear-btn-primary" data-type="reload" id="featureSearch" lay-filter="user-query" lay-submit>
                            <i class="layui-icon layui-icon-search"></i> 查询
                        </a>
                        <button class="pear-btn pear-btn-md" id="featureReset" type="button">
		                        <i class="layui-icon layui-icon-refresh"></i>
		                        重置
		                    </button>
                    </div>
                </form>
            </div>
        </div>
        <div class="layui-card">
            <div class="layui-card-body">
                <table id="user-table" lay-filter="user-table"></table>
            </div>
        </div>
    </body>

    <script id="user-toolbar" type="text/html">
        <button class="pear-btn pear-btn-primary pear-btn-md" lay-event="add">
		        <i class="layui-icon layui-icon-add-1"></i>
		        添加要素
		    </button>
        <button class="pear-btn pear-btn-danger pear-btn-md" lay-event="batchRemove">
		        <i class="layui-icon layui-icon-delete"></i>
		        删除
		    </button>
    </script>

    <script id="user-sex" type="text/html">
        {{#if (d.sex == 1) { }}
        <span>男</span> {{# }else if(d.sex == 2){ }}
        <span>女</span> {{# } }}
    </script>

    <script id="user-bar" type="text/html">
        <input type="checkbox" name="状态" valueId="{{d.id}}" valueElementName="{{d.elementName}}" valueElementType="{{d.elementType}}" lay-skin="switch" lay-text="启用|禁用" lay-filter="enabledState" {{ d.status=="1" ? "checked": "" }}>
        <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="detail">预览</a>
        <a class="layui-btn layui-btn-xs" lay-event="edit">修改</a>
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    </script>

    <script id="user-enable" type="text/html">
        <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="start">启用</a>
    </script>
    <script id="data-type" type="text/html">
        {{#if (d.elementType == 1) { }}
        <span>点</span> {{# }else if(d.elementType == 2){ }}
        <span>线</span> {{# }else if(d.elementType == 3){ }}
        <span>面</span> {{# } }}
    </script>
    <script id="createTime-type" type="text/html">
        <div>{{ layui.util.toDateString(d.createTime, 'yyyy-MM-dd HH:mm:ss') }}</div>
    </script>
    <script id="service-status" type="text/html">
        {{#if (d.status == 1) { }}
        <span style="color: #338528;">启用</span> {{# }else if(d.status == 0){ }}
        <span>禁用</span> {{# } }}
    </script>
    <!--		新增开始 -->
    <div class="site-text" id="service-window" style="margin: 5%; display: none" target="test123">
        <form class="layui-form" enctype="multipart/form-data" id="fm">
            <div class="layui-form-item">
                <label class="layui-form-label">要素名称</label>
                <div class="layui-input-block">
                    <input autocomplete="off" class="layui-input" id="elementName" lay-verify="required" maxlength="50" name="elementName" placeholder="请输入要素名称" required type="text">
                    <input id="status" name="status" type="hidden" value="1">
                    <div class="layui-form-mid layui-word-aux">必填项</div>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">要素描述</label>
                <div class="layui-input-block">
                    <textarea class="layui-textarea" id="remark" maxlength="200" name="remark" placeholder="请输入要素描述"></textarea>
                </div>
            </div>
            <label class="layui-form-label">业务主题</label>
            <div class="layui-form-item">
                <label class="layui-form-label">物业规划</label>
                <div class="layui-input-inline" id="guihua" style="width: 100%">

                </div>
                <label class="layui-form-label">物业产权</label>
                <div class="layui-input-inline" id="chanquan" style="width: 100%">

                </div>
                <label class="layui-form-label">资产财务</label>
                <div class="layui-input-inline" id="caiwu" style="width: 100%">

                </div>
                <label class="layui-form-label">物业经营</label>
                <div class="layui-input-inline" id="jingying" style="width: 100%">

                </div>
                <label class="layui-form-label">物业日常</label>
                <div class="layui-input-inline" id="richang" style="width: 100%">

                </div>
            </div>
        </form>

    </div>
    <!--		新增结束 -->
    <script src="../../component/layui/layui.js"></script>
    <script>
        
        var cumstomObj = {};
        layui.use(['table', 'form', 'jquery', 'upload'], function() {
            let table = layui.table;
            let form = layui.form;
            let $ = layui.jquery;
            let upload = layui.upload;

            let MODULE_PATH = "/system/business/";

            let cols = [
                [{
                        type: 'checkbox'
                    },
                    // {title: '缩略图', field: 'username', align:'center', width:100},
                    {
                        title: '要素名称',
                        field: 'elementName',
                        align: 'center'
                    }, {
                        title: '要素描述',
                        field: 'remark',
                        align: 'center'
                    }, {
                        title: '要素格式',
                        field: 'elementType',
                        align: 'center',
                        templet: '#data-type'
                    }, {
                        title: '要素状态',
                        field: 'status',
                        sort: true,
                        align: 'center',
                        templet: '#service-status'
                    }, {
                        title: '创建时间',
                        field: 'createTime',
                        sort: true,
                        align: 'center',
                        templet: '#createTime-type'
                    }, {
                        title: '操作',
                        toolbar: '#user-bar',
                        fixed: 'right',
                        align: 'center',
                        width: 300
                    }
                ]
            ];
            function loginStatusIntercept(e){
                console.log(e);
                layer.msg(e);
                setTimeout(()=>{
                    top.location.href = "/ftwgypt/login"
                },3000)
            }
            table.render({
                elem: '#user-table',
                url: '/one/element/getBusinessList',
                method: 'POST',
                contentType: 'application/json',
                where: {
                    order: 3,
                    orderDesc: 0
                },
                request: {
                    pageName: 'pageNo',//页码的参数名称，默认：page
                    limitName: 'pageSize' //每页数据量的参数名，默认：limit
                },
                parseData: function(res) { //res 即为原始返回的数据
                    if (res.errorCode === '401') {
                        loginStatusIntercept(res.msg)
                        return
                    }else{
                       return {
                            "createTime": null,
                            "createBy": null,
                            "updateTime": null,
                            "updateBy": null,
                            "remark": null,
                            "code": 200,
                            "msg": "...",
                            "count": res.data.total,
                            "data": res.data.list
                        }
                    }
                },
                id: 'user-table',
                page: true,
                cols: cols,
                skin: 'line',
                toolbar: '#user-toolbar',
                response: {
                    statusCode: 200 //成功的状态码，默认：0
                },
                initSort: {
					field: 'createTime',
					type: 'desc',
				},
                defaultToolbar: [{
                        layEvent: 'refresh',
                        icon: 'layui-icon-refresh',
                        title:'刷新'
                    }, 'filter'] // , 'print', 'exports'
            });

            //获取业务主题
            function getZhuTi() {
                $.ajax({
                    url: '/one/element/getBasicList',
                    type: 'GET',
                    dataType: "json",
                    success: function(result) {
                        if (result.errorCode === '401') {
                            loginStatusIntercept(result.msg)
                            return
                        }
                        var arr = result.data;
                        $("#guihua").html("");
                        $("#chanquan").html("");
                        $("#caiwu").html("");
                        $("#jingying").html("");
                        $("#richang").html("");
                        arr.forEach(item => {
                            var list = item.child;
                            list.forEach(items => {
                                if (!items.enabled && items.parentId == 1) {
                                    $("#guihua").append("<input type='radio' name='objectId' value='" + items.id + "' title='" + items.elementName + "' disabled>")
                                } else if (items.enabled && items.parentId == 1) {
                                    $("#guihua").append("<input type='radio' name='objectId' value='" + items.id + "' title='" + items.elementName + "'>")
                                } else if (!items.enabled && items.parentId == 2) {
                                    $("#chanquan").append("<input type='radio' name='objectId' value='" + items.id + "' title='" + items.elementName + "'disabled>")
                                } else if (items.enabled && items.parentId == 2) {
                                    $("#chanquan").append("<input type='radio' name='objectId' value='" + items.id + "' title='" + items.elementName + "'>")
                                } else if (!items.enabled && items.parentId == 3) {
                                    $("#caiwu").append("<input type='radio' name='objectId' value='" + items.id + "' title='" + items.elementName + "' disabled>")
                                } else if (items.enabled && items.parentId == 3) {
                                    $("#caiwu").append("<input type='radio' name='objectId' value='" + items.id + "' title='" + items.elementName + "'>")
                                } else if (!items.enabled && items.parentId == 4) {
                                    $("#jingying").append("<input type='radio' name='objectId' value='" + items.id + "' title='" + items.elementName + "' disabled>")
                                } else if (items.enabled && items.parentId == 4) {
                                    $("#jingying").append("<input type='radio' name='objectId' value='" + items.id + "' title='" + items.elementName + "' >")
                                } else if (!items.enabled && items.parentId == 5) {
                                    $("#richang").append("<input type='radio' name='objectId' value='" + items.id + "' title='" + items.elementName + "' disabled>")
                                } else if (items.enabled && items.parentId == 5) {
                                    $("#richang").append("<input type='radio' name='objectId' value='" + items.id + "' title='" + items.elementName + "' >")
                                }

                            })
                        })
                        layui.form.render('radio')
                    }
                })
            }

            table.on('sort(user-table)', function(obj) { //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
                // console.log(obj.field); //当前排序的字段名
                // console.log(obj.type); //当前排序类型：desc（降序）、asc（升序）、null（空对象，默认排序）

                var field = obj.field;
                var type = obj.type;
                var order = 1;
                var orderDesc = 0;
                if (field === 'createTime') {
                    order = 3;
                } else if (field === 'updateTime') {
                    order = 2;
                }

                if (type === "asc") {
                    orderDesc = 1
                } else if (type == "desc") {
                    orderDesc = 0;
                } else {
                    orderDesc = 0;
                    order = 2;
                }


                //尽管我们的 table 自带排序功能，但并没有请求服务端。
                //有些时候，你可能需要根据当前排序的字段，重新向服务端发送请求，从而实现服务端排序，如：
                table.reload('user-table', {
                    initSort: obj //记录初始排序，如果不设的话，将无法标记表头的排序状态。 layui 2.1.1 新增参数
                        ,
                    where: { //请求参数（注意：这里面的参数可任意定义，并非下面固定的格式）
                        order: order //排序字段   在接口作为参数字段  field order
                            ,
                        orderDesc: orderDesc //排序方式   在接口作为参数字段  field order
                    }
                });
            });

            table.on('tool(user-table)', function(obj) {

                var data = obj.data;
                if (obj.event === 'detail') {
                    // var pathname = top.location.href;
                    var JUMP_PATH = window.sessionStorage.envLocation + "/previewGeojson.html";
                    var modelContentValue = JSON.stringify(data.modelContent);
                    var themeType=data.themeType;
                    sessionStorage.spatialModel = modelContentValue;
                    sessionStorage.themeType= themeType ;
                    sessionStorage.previewUrl="";
                    window.open(JUMP_PATH);

                } else if (obj.event === 'edit') {
                    layer.open({
                        type: 1,
                        title: '修改业务要素',
                        shade: 0.1, //遮罩透明度
                        area: ['70%', '70%'],
                        content: $('#service-window'),
                        resize: true,
                        btn: ['确定', '取消'],
                        success: function(layero, index) {
                            $('#elementName').val(data.elementName);
                            $('#remark').val(data.remark);
                            $.ajax({
                                url: '/one/element/getBusinessById',
                                type: 'GET',
                                dataType: "json",
                                data: {
                                    id: data.id
                                },
                                success: function(result) {
                                    if (result.errorCode === '401') {
                                        loginStatusIntercept(result.msg)
                                        return
                                    }
                                    var arr = result.data.businessTheme;
                                    $("#guihua").html("");
                                    $("#chanquan").html("");
                                    $("#caiwu").html("");
                                    $("#jingying").html("");
                                    $("#richang").html("");
                                    arr.forEach(item => {
                                        var list = item.child;
                                        list.forEach(items => {
                                            if (!items.enabled && items.parentId == 1) {
                                                $("#guihua").append("<input type='radio' name='objectId' value='" + items.id + "' title='" + items.elementName + "' disabled>")
                                            } else if (items.enabled && items.parentId == 1) {
                                                $("#guihua").append("<input type='radio' name='objectId' value='" + items.id + "' title='" + items.elementName + "'>")
                                            } else if (!items.enabled && items.parentId == 2) {
                                                $("#chanquan").append("<input type='radio' name='objectId' value='" + items.id + "' title='" + items.elementName + "'disabled>")
                                            } else if (items.enabled && items.parentId == 2) {
                                                $("#chanquan").append("<input type='radio' name='objectId' value='" + items.id + "' title='" + items.elementName + "'>")
                                            } else if (!items.enabled && items.parentId == 3) {
                                                $("#caiwu").append("<input type='radio' name='objectId' value='" + items.id + "' title='" + items.elementName + "' disabled>")
                                            } else if (items.enabled && items.parentId == 3) {
                                                $("#caiwu").append("<input type='radio' name='objectId' value='" + items.id + "' title='" + items.elementName + "'>")
                                            } else if (!items.enabled && items.parentId == 4) {
                                                $("#jingying").append("<input type='radio' name='objectId' value='" + items.id + "' title='" + items.elementName + "' disabled>")
                                            } else if (items.enabled && items.parentId == 4) {
                                                $("#jingying").append("<input type='radio' name='objectId' value='" + items.id + "' title='" + items.elementName + "' >")
                                            } else if (!items.enabled && items.parentId == 5) {
                                                $("#richang").append("<input type='radio' name='objectId' value='" + items.id + "' title='" + items.elementName + "' disabled>")
                                            } else if (items.enabled && items.parentId == 5) {
                                                $("#richang").append("<input type='radio' name='objectId' value='" + items.id + "' title='" + items.elementName + "' >")
                                            }

                                        })
                                    })
                                    $("input[name=objectId][value=" + data.objectId + "]").prop("checked", true, )
                                    layui.form.render('radio')
                                }
                            })
                        },
                        yes: function(index, layero) {
                            if (!$("#elementName").val()) {
                                layer.msg('要素名称不能为空', {
                                    icon: 2,
                                    time: 1000
                                });
                                return;
                            }
                            $.ajax({
                                url: "/one/element/updateBusiness",
                                type: "POST",
                                data: JSON.stringify({
                                    id: data.id,
                                    elementName: $('#elementName').val(),
                                    remark: $('#remark').val(),
                                    objectId: $('input[name="objectId"]:checked').val()
                                }),
                                dataType: "json",
                                contentType: "application/json; charset=UTF-8",
                                success: function(data) {
                                    if (data.errorCode === '401') {
                                        loginStatusIntercept(data.msg)
                                        return
                                    }
                                    if (data.success) {
                                        layer.alert('修改成功', {
                                            icon: 1,
                                            title: '提示'
                                        }, function(i) {
                                            layer.close(i);
                                            layer.close(index); //关闭弹出层
                                            $("#fm")[0].reset() //重置form
                                        });
                                        table.reload('user-table', { //重载表格
                                            page: {
                                                curr: obj.curr
                                            }
                                        })
                                    } else {
                                        layer.msg("修改失败,失败原因:" + data.msg, {
                                            icon: 5
                                        });
                                    }
                                }
                            });
                        }
                    });
                    //业务删除
                } else if (obj.event === 'del') {
                    layer.confirm('确认删除？', {
                        icon: 3,
                        title: '提示'
                    }, function(index) {
                        // console.log(data);
                        let ids = data.id;
                        let arrids = [];
                        arrids.push(ids)
                        console.log(arrids);
                        $.ajax({
                            url: "/one/element/deleteBusiness",
                            type: "POST",
                            data: {
                                ids: ids
                            },
                            dataType: "json",
                            success: function(data) {
                                if (data.errorCode === '401') {
                                    loginStatusIntercept(data.msg)
                                    return
                                }
                                if (data.success) {
                                    //删除这一行
                                    obj.del();
                                    //关闭弹框
                                    layer.close(index);
                                    layer.msg("删除成功", {
                                        icon: 6
                                    });
                                } else {
                                    layer.msg("删除失败", {
                                        icon: 5
                                    });
                                }
                            }
                        });
                    });
                }
            });

            $("#demoReload").unbind("keydown").keydown(function (e) {//当按下按键时
				e.stopPropagation()
				var key = e.keyCode || e.charCode || e.which;
				if (key == 13) {
					e.preventDefault()
					$("#featureSearch").trigger('click');
				}
        	});
            
            //查询(支持模糊查询)
            $('#featureSearch').on('click', function() {
                var active = {
                    reload: function() {
                        var demoReload = $('#demoReload');
                        //执行重载
                        table.reload('user-table', {
                            page: {
                                curr: 1 //重新从第 1 页开始
                            },
                            where: {
                                elementName: demoReload.val()
                            }
                        }, 'data');
                    }
                };
                var type = $(this).data('type');
                active[type] ? active[type].call(this) : '';
            });

            //重置
            $('#featureReset').on('click', function() {
                var demoReload = $('#demoReload');
                demoReload.val("")
                    //执行重载
                table.reload('user-table', {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    },
                    where: {
                        elementName: demoReload.val()
                    }
                }, 'data');
            });

            table.on('toolbar(user-table)', function(obj) {
                if (obj.event === 'add') {
                    cumstomObj.add();
                } else if (obj.event === 'refresh') {
                    cumstomObj.refresh();
                } else if (obj.event === 'batchRemove') {
                    cumstomObj.batchRemove(obj);
                } else if (obj.event === 'view') {
                    cumstomObj.view(obj);
                }
            });

            //启用禁用
            form.on('switch(enabledState)', function(obj) {
                //获取自定义标签valueId等上的值
                var switch_id = obj.elem.attributes['valueId'].nodeValue;
                var switch_ElementName = obj.elem.attributes['valueElementName'].nodeValue;
                var validFlag = Number(obj.elem.checked); //转为 0、1
                console.log(validFlag);
                $.ajax({
                    url: "/one/element/enableOrDisabled",
                    type: "POST",
                    data: JSON.stringify({
                        id: switch_id,
                        elementName: switch_ElementName,
                        status: validFlag
                    }),
                    dataType: "json",
                    contentType: "application/json; charset=UTF-8",
                    success: function(data) {
                        if (data.errorCode === '401') {
                            loginStatusIntercept(data.msg)
                            return
                        }
                        if (data.success) {
                            table.reload('user-table');
                            console.log(obj.elem.checked);
                            layer.msg('要素状态：' + (obj.elem.checked ? '启用' : '禁用'), {
                                icon: 1
                            });
                        } else {
                            layer.msg("失败,失败原因:" + data.msg, {
                                icon: 2
                            });
                            table.reload('user-table');
                        }
                    }
                });
            });

            form.on('submit(demo1)', function(data) {

            });

            //新增业务要素
            cumstomObj.add = function() {
                $('#elementName').val("");
                $('#remark').val("");
                $('input[name=objectId]').prop('checked', false);
                form.render('radio');
                layer.open({
                    type: 1,
                    title: '添加业务要素',
                    shade: 0.1,
                    area: ['70%', '70%'],
                    content: $('#service-window'),
                    resize: true,
                    btn: ['确定', '取消'],
                    success: function(layero, index) {
                        getZhuTi()
                    },
                    yes: function(index, layero) {
                        if (!$('#elementName').val()) {
                            layer.msg("请输入要素名称", {
                                icon: 2
                            });
                            return;
                        } else if (!$('input[name="objectId"]:checked').val()) {
                            layer.msg("请选择业务主题", {
                                icon: 2
                            });
                            return;
                        } else {
                            $.ajax({
                                url: '/one/element/addBusiness',
                                type: 'POST',
                                dataType: "json",
                                contentType: "application/json; charset=UTF-8",
                                data: JSON.stringify({
                                    elementName: $('#elementName').val(),
                                    remark: $('#remark').val(),
                                    objectId: $('input[name="objectId"]:checked').val()
                                }),
                                success: function(data) {
                                    if (data.errorCode === '401') {
                                        loginStatusIntercept(data.msg)
                                        return
                                    }
                                    if (data.success) {
                                        layer.msg('添加成功', {
                                            icon: 1,
                                            time: 1000
                                        }, function(i) {
                                            layer.close(i);
                                            layer.close(index); //关闭弹出层
                                            $("#fm")[0].reset() //重置form
                                        });
                                        table.reload('user-table');
                                    } else {
                                        layer.msg("添加失败,失败原因:" + data.msg, {
                                            icon: 5
                                        });
                                    }
                                },
                                error: function(err) {
                                    layer.msg("后台请求出错:" + err.responseText, {
                                        icon: 2,
                                        time: 1000
                                    });
                                    layer.close(loading);
                                }
                            })
                        }
                    },
                });
            };

            cumstomObj.remove = function(obj) {
                layer.confirm('确认删除该要素吗？', {
                    icon: 3,
                    title: '提示'
                }, function(index) {
                    layer.close(index);
                    let loading = layer.load();
                    $.ajax({
                        url: MODULE_PATH + "remove/" + obj.data['userId'],
                        dataType: 'json',
                        type: 'delete',
                        data: {
                            ids: ids
                        },
                        success: function(result) {
                            if (result.errorCode === '401') {
                                loginStatusIntercept(result.msg)
                                return
                            }
                            layer.close(loading);
                            if (result.success) {
                                layer.msg(result.msg, {
                                    icon: 1,
                                    time: 1000
                                }, function() {
                                    obj.del();
                                });
                            } else {
                                layer.msg(result.msg, {
                                    icon: 2,
                                    time: 1000
                                });
                            }
                        }
                    })
                });
            }

            cumstomObj.batchRemove = function(obj) {
                let data = table.checkStatus(obj.config.id).data;
                if (data.length === 0) {
                    layer.msg("未选中数据", {
                        icon: 3,
                        time: 1000
                    });
                    return false;
                }
                let ids = "";
                for (let i = 0; i < data.length; i++) {
                    ids += data[i].id + ",";
                }
                ids = ids.substr(0, ids.length - 1);
                console.log(ids);
                layer.confirm('确认删除该要素吗？', {
                    icon: 3,
                    title: '提示'
                }, function(index) {
                    layer.close(index);
                    let loading = layer.load();
                    $.ajax({
                        url: '/one/element/deleteBusiness',
                        dataType: 'json',
                        type: 'POST',
                        data: {
                            ids: ids
                        },
                        success: function(result) {
                            if (result.errorCode === '401') {
                                loginStatusIntercept(result.msg)
                                return
                            }
                            layer.close(loading);
                            if (result.success) {
                                layer.msg(result.msg, {
                                    icon: 1,
                                    time: 1000
                                }, function() {
                                    table.reload('user-table');
                                });
                            } else {
                                layer.msg(result.msg, {
                                    icon: 2,
                                    time: 1000
                                });
                            }
                        }
                    })
                });
            }

            cumstomObj.refresh = function(param) {
                table.reload('user-table');
            }
        })
    </script>
</body>

</html>
